<!-- 新增/修改弹框 -->
<template>
  <!-- 新增/修改弹窗 -->
  <el-dialog
    v-model="dialogAddCert.visible"
    :title="dialogAddCert.title"
    draggable
    :width="900"
    close-icon="CloseBold"
    :close-delay="200"
    style="margin-top: 5vh"
    @close="closeDialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100"
      size=""
      style="padding-right: 10px; overflow: auto"
    >
      <el-row
        style="border-left: 5px solid #3b98f7; margin-left: 50px; text-indent: 2em; line-height: 30px; font-weight: 600"
        >证书信息</el-row
      >
      <!-- 职业技能证书 -->
      <el-row v-if="formData.certificateType == 1" justify="start" style="margin-top: 10px">
        <el-col :span="8">
          <el-form-item label="技能分类" prop="skillClassification">
            <el-select
              v-model="formData.skillClassification"
              placeholder="请选择"
              clearable
              @change="changeSkillClassification"
            >
              <el-option
                v-for="item in skillClassifications"
                :key="item.value"
                :label="item.label"
                :value="item.label"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="技能类别" prop="skillCategory">
            <el-select v-model="formData.skillCategory" placeholder="请选择" clearable>
              <el-option v-for="item in skillCategorys" :key="item.value" :label="item.label" :value="item.label" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="技能等级" prop="skillLevel">
            <el-select v-model="formData.skillLevel" placeholder="请选择" clearable>
              <el-option v-for="item in skillLevels" :key="item.value" :label="item.label" :value="item.label" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="证书编号" prop="certificateNo">
            <el-input v-model="formData.certificateNo" placeholder="请输入证书编号" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="发证日期" prop="issueDate">
            <el-date-picker
              v-model="formData.issueDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="发证机关" prop="issuingAuthority">
            <el-input v-model="formData.issuingAuthority" placeholder="请输入发证机关" />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 执业注册证书 -->
      <el-row v-if="formData.certificateType == 5" justify="start" style="margin-top: 10px">
        <el-col :span="8">
          <el-form-item label="执业注册类型" prop="skillClassification">
            <el-select
              v-model="formData.skillClassification"
              placeholder="请选择"
              clearable
              @change="changeSkillClassification"
            >
              <el-option
                v-for="item in skillClassifications"
                :key="item.value"
                :label="item.label"
                :value="item.label"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="资质证书状态" prop="status">
            <el-select v-model="formData.status" placeholder="请选择" clearable>
              <el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.label" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="注册证书编号" prop="certificateNo">
            <el-input v-model="formData.certificateNo" placeholder="请输入证书编号" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="执业印章号" prop="practicingSealNumber">
            <el-input v-model="formData.practicingSealNumber" placeholder="请输入证书编号" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="发证日期" prop="issueDate">
            <el-date-picker
              v-model="formData.issueDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="注册有效期" prop="registerEndDate">
            <el-date-picker
              v-model="formData.registerEndDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-table :data="formData.speciality" style="width: 100%">
            <el-table-column label="注册专业编号" prop="code">
              <template #default="{ row, $index }">
                <el-form-item :prop="`speciality.${$index}.code`" :rules="specialityRules.code">
                  <el-input v-model="row.code" placeholder="请输入注册专业编号" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="注册专业名称" prop="specialityName">
              <template #default="{ row, $index }">
                <el-form-item :prop="`speciality.${$index}.specialityName`" :rules="specialityRules.specialityName">
                  <el-select v-model="row.specialityName" placeholder="请选择" clearable>
                    <el-option
                      v-for="item in certificateSpecialitys"
                      :key="item.value"
                      :label="item.label"
                      :value="item.label"
                    />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="注册专业起始日期" prop="startDate">
              <template #default="{ row, $index }">
                <el-form-item :prop="`speciality.${$index}.startDate`" :rules="specialityRules.startDate">
                  <el-date-picker
                    v-model="row.startDate"
                    type="date"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    placeholder="选择日期"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="注册专业截止日期" prop="endDate">
              <template #default="{ row, $index }">
                <el-form-item :prop="`speciality.${$index}.endDate`" :rules="specialityRules.endDate">
                  <el-date-picker
                    v-model="row.endDate"
                    type="date"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    placeholder="选择日期"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="right">
              <template #header>
                <el-button type="primary" link @click="handleAdd">新增注册专业</el-button>
              </template>
              <template #default="scope">
                <el-button size="small" link type="danger" @click="handleDelete(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <!-- 岗位证书 -->
      <el-row v-if="formData.certificateType == 3" justify="start" style="margin-top: 10px">
        <el-col :span="8">
          <el-form-item label="岗位证书专业" prop="certificateSpeciality">
            <el-select v-model="formData.certificateSpeciality" placeholder="请选择" clearable>
              <el-option
                v-for="item in certificateSpecialitys"
                :key="item.value"
                :label="item.label"
                :value="item.label"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="证书名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入证书名称" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="证书编号" prop="certificateNo">
            <el-input v-model="formData.certificateNo" placeholder="请输入证书编号" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="发证日期" prop="issueDate">
            <el-date-picker
              v-model="formData.issueDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="有效期至" prop="registerEndDate">
            <el-date-picker
              v-model="formData.registerEndDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="发证机关" prop="issuingAuthority">
            <el-input v-model="formData.issuingAuthority" placeholder="请输入发证机关" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="证书附件" prop="atachment">
            <el-upload
              v-model:file-list="fileList"
              :action="actionUrl"
              multiple
              :limit="5"
              accept=".doc,.docx,.pdf,.jpg,.png,.xls,.xlsx"
              :on-exceed="handleUploadExceed"
              :on-success="handleUploadSuccess"
              :on-preview="handleUploadPreview"
            >
              <el-button plain size="small">上传附件</el-button>
              <template #tip>
                <div class="el-upload__tip">仅支持上传doc,docx,xls,xlsx,pdf,jpg,png且不大于5M的文件</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 职称证书 -->
      <el-row v-if="formData.certificateType == 4" justify="start" style="margin-top: 10px">
        <el-col :span="8">
          <el-form-item label="专业名称" prop="certificateSpeciality">
            <el-input v-model="formData.certificateSpeciality" placeholder="请输入专业名称" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="资格名称、职称等级" prop="skillLevels">
            <el-select v-model="formData.skillLevel" placeholder="请选择" clearable>
              <el-option v-for="item in skillLevels" :key="item.value" :label="item.label" :value="item.label" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="评审组织" prop="reviewOrganization">
            <el-input v-model="formData.reviewOrganization" placeholder="请输入评审组织" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="审批机关" prop="issuingAuthority">
            <el-input v-model="formData.issuingAuthority" placeholder="请输入审批机关" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="批准文号" prop="certificateNo">
            <el-input v-model="formData.certificateNo" placeholder="请输入批准文号" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="批准时间" prop="issueDate">
            <el-date-picker
              v-model="formData.issueDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="证书附件" prop="attachments">
            <el-upload
              v-model:file-list="fileList"
              :action="actionUrl"
              multiple
              :limit="5"
              accept=".doc,.docx,.pdf,.jpg,.png,.xls,.xlsx"
              :on-exceed="handleUploadExceed"
              :on-success="handleUploadSuccess"
              :on-preview="handleUploadPreview"
            >
              <el-button plain size="small">上传附件</el-button>
              <template #tip>
                <div class="el-upload__tip">仅支持上传doc,docx,xls,xlsx,pdf,jpg,png且不大于5M的文件</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 安装证书 -->
      <el-row v-if="formData.certificateType == 2" justify="start" style="margin-top: 10px">
        <el-col :span="8">
          <el-form-item label="证书名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入证书名称" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="证书编号" prop="certificateNo">
            <el-input v-model="formData.certificateNo" placeholder="请输入证书编号" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="发证机关" prop="issuingAuthority">
            <el-input v-model="formData.issuingAuthority" placeholder="请输入发证机关" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="发证日期" prop="issueDate">
            <el-date-picker
              v-model="formData.issueDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="证书有效期" prop="registerEndDate">
            <el-date-picker
              v-model="formData.registerEndDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 其他证书 -->
      <el-row v-if="formData.certificateType == 6" justify="start" style="margin-top: 10px">
        <el-col :span="8">
          <el-form-item label="证书名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入证书名称" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="证书编号" prop="certificateNo">
            <el-input v-model="formData.certificateNo" placeholder="请输入证书编号" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="发证机关" prop="issuingAuthority">
            <el-input v-model="formData.issuingAuthority" placeholder="请输入发证机关" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="发证日期" prop="issueDate">
            <el-date-picker
              v-model="formData.issueDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="证书有效期" prop="registerEndDate">
            <el-date-picker
              v-model="formData.registerEndDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog_footer">
        <el-button type="primary" @click="handleSubmit">{{ dialogAddCert.footBtn }}</el-button>
        <el-button @click="closeDialog(false)">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { PersonCertificateForm, PersonCertificateSpecialityForm } from "@/api/worker/types";
import { getDicts } from "@/store/modules/dict";
import { FormRules } from "element-plus/es/components/form/src/types";
import type { UploadUserFile } from "element-plus";

//声明变量
const props = defineProps({
  dialogAddCert: {
    type: Object,
    default: () => ({
      visible: false,
      title: "新增",
      footBtn: "确认新增",
      id: 0,
    }),
  },
});

const emit = defineEmits(["sendClose", "saveInfo"]);
// 上传地址
const actionUrl = ref(`${import.meta.env.VITE_APP_BASE_API}/api/v1/common/upload`);
// 弹窗数据
const { dialogAddCert } = toRefs(props);
// 证书数据集
const personCertificateTrees = getDicts("personCertificateTrees");
//上传文件列表
const fileList = ref<UploadUserFile[]>([]);

//下拉选项
const skillClassifications = ref([] as any[]);
const skillCategorys = ref([] as any[]);
const skillLevels = ref([] as any[]);
const statusList = ref([] as any[]);
const certificateSpecialitys = ref([] as any[]);

const formData = reactive<PersonCertificateForm>({
  certificateType: 0,
});
const formRef = ref(ElForm);

// 监听技能分类
const changeSkillClassification = (value: string) => {
  if (formData.certificateType == 1)
    skillCategorys.value = skillClassifications.value.find((i: any) => i.label == value).children;
};

const handleDelete = (index: number) => {
  formData.speciality?.splice(index, 1);
};

const handleAdd = () => {
  if (!formData.speciality) formData.speciality = [];
  formData.speciality.push({ code: "", specialityName: "", startDate: "", endDate: "" });
};

const validatorAttachment = function (rule: any, value: any, callback: any) {
  if (fileList.value.length == 0) {
    callback(new Error("请上传附件!"));
    return;
  } else {
    callback();
  }
};
const rules = reactive<FormRules<PersonCertificateForm>>({});
const specialityRules = reactive<FormRules<PersonCertificateSpecialityForm>>({
  code: [{ required: true, message: "", trigger: "blur" }],
  specialityName: [{ required: true, message: "", trigger: "blur" }],
  startDate: [{ required: true, message: "", trigger: "blur" }],
  endDate: [{ required: true, message: "", trigger: "blur" }],
});

const initForm = () => {
  /* 初始化表单 */
  formData.attachments = [];
  formData.speciality = [];
  fileList.value = [];
  formData.certificateType = dialogAddCert.value.id;

  /* 初始化可选项 */
  // 扩展字段1： 1 分类  2 专业  3  状态  4等级
  let parent = personCertificateTrees.find((item: any) => item.value == formData.certificateType);
  if (parent) {
    skillClassifications.value = parent.children.filter((item: any) => item.extend1 == 1);
    skillLevels.value = parent.children.filter((item: any) => item.extend1 == 4);
    statusList.value = parent.children.filter((item: any) => item.extend1 == 3);
    certificateSpecialitys.value = parent.children.filter((item: any) => item.extend1 == 2);
  }

  /* 初始化表单验证规则 */
  if (formData.certificateType == 1) {
    rules.skillClassification = [{ required: true, message: "请选择技能分类", trigger: "blur" }];
    rules.skillCategory = [{ required: true, message: "请选择技能类别", trigger: "blur" }];
    rules.skillLevel = [{ required: true, message: "请选择技能等级", trigger: "blur" }];
    rules.certificateNo = [{ required: true, message: "请输入证书编号", trigger: "blur" }];
    rules.issuingAuthority = [{ required: true, message: "请输入发证机关", trigger: "blur" }];
  }
  if (formData.certificateType == 2) {
    rules.name = [{ required: true, message: "请输入证书名称", trigger: "blur" }];
    rules.certificateNo = [{ required: true, message: "请输入证书编号", trigger: "blur" }];
    rules.issuingAuthority = [{ required: true, message: "请输入发证机关", trigger: "blur" }];
    rules.holder = [{ required: true, message: "请输入持有人", trigger: "blur" }];
    rules.issueDate = [{ required: true, message: "请选择发证日期", trigger: "blur" }];
    rules.registerEndDate = [{ required: true, message: "请选择证书有效期", trigger: "blur" }];
  }
  if (formData.certificateType == 3) {
    rules.certificateSpeciality = [{ required: true, message: "请选择证书专业", trigger: "blur" }];
    rules.certificateNo = [{ required: true, message: "请输入证书编号", trigger: "blur" }];
    rules.issueDate = [{ required: true, message: "请选择发证日期", trigger: "blur" }];
    rules.registerEndDate = [{ required: true, message: "请选择证书有效期", trigger: "blur" }];
    rules.issuingAuthority = [{ required: true, message: "请输入发证机关", trigger: "blur" }];
  }
  if (formData.certificateType == 4) {
    rules.certificateSpeciality = [{ required: true, message: "请输入专业名称", trigger: "blur" }];
    rules.skillLevel = [{ required: true, message: "请选择职称等级", trigger: "blur" }];
    rules.reviewOrganization = [{ required: true, message: "请输入审批机关", trigger: "blur" }];
    rules.certificateNo = [{ required: true, message: "请输入批准文号", trigger: "blur" }];
    rules.issueDate = [{ required: true, message: "请选择批准日期", trigger: "blur" }];
    rules.attachments = [{ message: "请上传附件", trigger: "blur", validator: validatorAttachment }];
  }
  if (formData.certificateType == 5) {
    rules.skillClassification = [{ required: true, message: "请选择执业注册类型", trigger: "blur" }];
    rules.status = [{ required: true, message: "请选择资质证书状态", trigger: "blur" }];
    rules.certificateNo = [{ required: true, message: "请输入注册证书编号", trigger: "blur" }];
    rules.practicingSealNumber = [{ required: true, message: "请选择执业印章编号", trigger: "blur" }];
    rules.issueDate = [{ required: true, message: "请选择发证日期", trigger: "blur" }];
    rules.registerEndDate = [{ required: true, message: "请选择注册有效期", trigger: "blur" }];
  }
  if (formData.certificateType == 6) {
    rules.name = [{ required: true, message: "请输入证书名称", trigger: "blur" }];
    rules.certificateNo = [{ required: true, message: "请输入证书编号", trigger: "blur" }];
    rules.issuingAuthority = [{ required: true, message: "请输入发证机关", trigger: "blur" }];
    rules.issueDate = [{ required: true, message: "请选择发证日期", trigger: "blur" }];
    rules.registerEndDate = [{ required: true, message: "请选择证书有效期", trigger: "blur" }];
  }
};

watch(
  () => dialogAddCert.value.visible,
  () => {
    if (dialogAddCert.value.visible) {
      initForm();
    }
  }
);

/* 附件上传 */
const handleUploadPreview = (file: any) => {
  ElMessage.info(file.url);
};
const handleUploadExceed = () => {
  ElMessage.error("最多上传5个附件");
};
const handleUploadSuccess = (response: any) => {
  console.log(fileList);
  if (response.type === 0) {
    if (response.success) {
    } else {
      ElMessage.error(response.msg);
    }
  } else {
    ElMessage.error(response.msg);
  }
};

onMounted(async () => {});

/**
 * 关闭弹窗
 */
function closeDialog(needRefresh: boolean) {
  emit("sendClose", needRefresh);
  resetForm();
}

/**
 * 重置表单
 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
}

/**
 * 项目表单提交
 */
function handleSubmit() {
  formRef.value.validate((valid: any) => {
    if (valid) {
      if (fileList.value.length > 0) {
        formData.attachments = [];
        fileList.value.forEach((item: any) => {
          if (item.status === "success") {
            if (item.response) {
              if (formData.attachments) {
                formData.attachments.push({ attachmentId: item.response.data, attachmentName: item.name });
              }
            }
          }
        });
      }
      let temp = JSON.parse(JSON.stringify(formData));
      emit("saveInfo", temp, temp.certificateType);
      closeDialog(true);
    }
  });
}
</script>

<style lang="scss" scoped>
:deep(.el-form-item) {
  flex-wrap: wrap;
}

:deep(.el-input) {
  width: 100%;
}

:deep(.el-select) {
  width: 100%;
}
:deep(.el-cascader) {
  width: 100%;
}
:deep(.el-input__wrapper) {
  width: 100%;
}

:deep(.el-form-item__label) {
  color: #696868;
  font-size: 13px;
}
:deep(.el-upload__tip) {
  display: inline-block;
  margin-left: 10px;
}
:deep(.el-table .el-form-item__content) {
  margin-left: 0 !important;
}
</style>
